package com.yunhe.openapi.util;

import com.yunhe.common.util.MD5Util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 加签
 */
public class SignEncodeUtil {
    private static final String salt = "@yunhe";

    public static String encode(Map<String, String> params, String accessKey, String secretKey){
        //情况可能冲突的key
        params.remove("sign");
        params.remove("accessKey");
        params.remove("secretKey");

        //1：生成时间戳和唯一标识
        Long timestamp = System.currentTimeMillis();
        String once = UUID.randomUUID().toString();
        params.put("timestamp", String.valueOf(timestamp));
        params.put("once", once);

        //System.out.println(JSONUtil.toJsonStr(params));

        // 2：参数排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 3：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        for (String key : keys) {
            if(query.length() > 0){
                query.append("&");
            }
            query.append(key).append("=").append(params.get(key));
        }
        //secretKey
        query.append("&secretKey=").append(secretKey);

        //4：md5加密
        return MD5Util.encode(query.toString(), salt);

        /*String sign = "sign=" + MD5Util.encode(query.toString()) + "&accessKey=" + accessKey;
        return sign;*/
    }

    public static void main(String[] args){
        Map<String, String> params = new HashMap(){{
            put("a", "a1");
            put("d", "d1");
            put("c", "c1");
        }};
        String accessKey = "accessKey";
        String secretKey = "secretKey";
        String sign = encode(params, accessKey, secretKey);
        System.out.println(sign);
    }
}
